package org.example.utils.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.annotation.LogTrace;
import org.example.dao.entity.user.ULabel;
import org.example.skytool.commom.ContextUtil;
import org.example.skytool.json.JackSonUtil;
import org.example.skytool.redis.RedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static org.example.skytool.redis.RedisConstants.*;
/**
 * @author 22449
 */
@Component
public class RedisLabelService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private ContextUtil contextUtil;

    private String getLabelTotalListKey(String version){
        String key = LABEL_MOUDLE + LABEL_TOTAL_CONTROLLER + LABEL_TOTAL_LIST_KIND + version;
        return key;
    }

    public String getLabelTotalListKeyVersion(){
        String key = LABEL_MOUDLE + LABEL_TOTAL_CONTROLLER + LABEL_TOTAL_LIST_VERSION_KIND;
        return key;
    }

    /**
     * 插入label缓存
     */
    public void setLabelTotalList(List<ULabel> list,String version){
        List<String> strs = new ArrayList<>(list.size());
        for(ULabel label : list){
            strs.add(JackSonUtil.encode(label));
        }
        redisUtils.listRightAddAll(getLabelTotalListKey(version),strs.toArray(new String[0]));
    }


    /**
     * 分页获取label缓存
     */
    @LogTrace
    public IPage<ULabel> getLabelTotalList(Integer start, Integer limit){
        String version = redisUtils.stringGet(getLabelTotalListKeyVersion());
        IPage<ULabel> uLabelIpage = new Page<>();
        List<String> list = redisUtils.listGet(getLabelTotalListKey(version),start-1,limit);
        List<ULabel> list1 = new ArrayList<>(list.size());
        for(String temp : list){
            list1.add(JackSonUtil.parse(ULabel.class,temp));
        }
        uLabelIpage.setRecords(list1);
        uLabelIpage.setCurrent(start);
        uLabelIpage.setSize(limit);
        uLabelIpage.setTotal(redisUtils.listGetSize(getLabelTotalListKey(version)));
        uLabelIpage.setPages((long) Math.ceil(uLabelIpage.getTotal()/limit));
        return uLabelIpage;
    }

    /**
     * 清空label缓存
     */
    public void delLabelTotalList(String version){
        redisUtils.del(getLabelTotalListKey(version));
    }


}
